package com.opal.system.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.opal.consts.CommonConst;
import com.opal.domain.ReturnMessageData;
import com.opal.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.opal.system.entity.ConditionSelectTbmSignhEntity;
import com.opal.model.DataGridData;
import com.opal.system.entity.TbmSignbExtend;
import com.opal.system.entity.TbmSignhExtend;
import com.opal.system.entity.table.BdDefdoc;
import com.opal.system.entity.table.BdPsndoc;
import com.opal.system.entity.table.OpalUser;
import com.opal.system.entity.table.OrgDeptExtend;
import com.opal.system.entity.table.OrgHrorg;
import com.opal.system.entity.table.TbmSignh;
import com.opal.system.entity.table.TbmSignreg;
import com.opal.system.mapper.oracle.SignCardSingleMapper;
import com.opal.system.service.SignCardSingleService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SignCardSingleServiceImpl implements SignCardSingleService {

	@Autowired
	private SignCardSingleMapper signCardSingleMapper;
	
	
	public OpalUser getUser() {
       Subject subject = SecurityUtils.getSubject();
       return  (OpalUser) subject.getPrincipal();
        
	}
	
	@Override
	public DataGridData conditionSelectTbmSignhService(ConditionSelectTbmSignhEntity conditionSelectTbmSignhEntit) {
		OpalUser user = getUser();
		if (user == null) {
			return new DataGridData(404, null) ;
		}
		DataGridData dg = null;
		// 获取当前的组织
		CommonConst.currentPkOrg.put(user.getUserId(),conditionSelectTbmSignhEntit.getPkOrg());

		// 获取年和月
		String beginSignDate = conditionSelectTbmSignhEntit.getBeginSignDate();
		String endSignDate = conditionSelectTbmSignhEntit.getEndSignDate();

		if(!StringUtils.isBlank(beginSignDate) && !StringUtils.isBlank(endSignDate)) {
			String[] begin = beginSignDate.split("-");
			String[] end = endSignDate.split("-");
			// 判断开始和结束的日期 2018 2019 要求不能
			if (Integer.parseInt(begin[0]) > Integer.parseInt(end[0])) {
				dg = new DataGridData(500, "结束日期小于开始日期！");
				return dg;
			} else {
				// 年份相同，判断月份
				if(Integer.parseInt(begin[0]) == Integer.parseInt(end[0])) {
					if (Integer.parseInt(begin[1]) > Integer.parseInt(end[1])) {
						dg = new DataGridData(500, "结束日期小于开始日期！");
						return dg;
					}
				}
				// 月份相同，判断日期
				if (Integer.parseInt(begin[1]) == Integer.parseInt(end[1])) {
					if (Integer.parseInt(begin[2]) > Integer.parseInt(end[2])) {
						// 返回提示数据
						dg = new DataGridData(500, "结束日期小于开始日期！");
						return dg;
					}
				}
			}
		}
		// 根据pkDepts获取部门的 pkDeptVs
		List<String> pkDepts = conditionSelectTbmSignhEntit.getPkDepts();
		if (pkDepts != null && pkDepts.size() > 0) {
			conditionSelectTbmSignhEntit.setPkDeptVs(signCardSingleMapper.getDeptPkVid(pkDepts));
		}
		//处理分页
		conditionSelectTbmSignhEntit.processingPageOracle(conditionSelectTbmSignhEntit.getPage(),conditionSelectTbmSignhEntit.getRows());
		//查询总数
		int result=signCardSingleMapper.conditionSelectTbmSignhCountMapper(conditionSelectTbmSignhEntit);
		if (result>0){
			// 查询数据
			dg = new DataGridData();
			dg.setTotal(result);
			dg.setRows(signCardSingleMapper.conditionSelectTbmSignhMapper(conditionSelectTbmSignhEntit));
			dg.setStatu(200);
		} else {
			dg = new DataGridData();
			dg.setStatu(300);
			dg.setMessage("没有相关的数据！");
		}
		return dg;
	}


	@Override
	public DataGridData getTbmSignbByPkSignhService(TbmSignhExtend tbmSignhExtend) {
		OpalUser user = getUser();
		if (user == null) {
			return new DataGridData(404, null);
		}
		DataGridData dg = null;
		String pkSignh = tbmSignhExtend.getPkSignh();
		// 信息
		CommonConst.currentPkSignh.put(user.getUserId(),pkSignh);
		CommonConst.currentbillCode.put(user.getUserId(), tbmSignhExtend.getBillCode());
		List<TbmSignbExtend> tbmSignbs = signCardSingleMapper.getTbmSignbByPkSignh(pkSignh);
		int size = tbmSignbs.size();
		dg = new DataGridData(200, "成功");
		// 封存查询总数用于进行判断是否全部删除
		for (TbmSignbExtend tbmSignb : tbmSignbs) {
			tbmSignb.setTotal(size);
		}
		dg.setRows(tbmSignbs);
		return dg;
	}

	@Override
	public List<OrgHrorg> selectAllOrgHrorgService() {
		return signCardSingleMapper.selectAllOrgHrorg();
	}

	@Override
	public List<OrgDeptExtend> selectAllOrgDeptService() {
		// 获取所有部门信息
		List<OrgDeptExtend> orgDepts = signCardSingleMapper.selectAllOrgDept();
//		// 存储map
//		Map<String, OrgDeptExtend> mapOrgDept = new HashMap<String, OrgDeptExtend>();
//		List<OrgDeptExtend> parent = new ArrayList<OrgDeptExtend>();
//		for (OrgDeptExtend orgDept : orgDepts) {
//			mapOrgDept.put(orgDept.getPkDept(), orgDept);
//			if (orgDept.getPkFatherorg().equals("~")) {
//				parent.add(orgDept);
//			}
//		}
//		for (OrgDeptExtend orgDept : orgDepts) {
//			// 从map中查找到父对象，把自己存进父对象的属性Children中
//			OrgDeptExtend orgDeptParent = mapOrgDept.get(orgDept.getPkFatherorg());
//			if (orgDeptParent != null) {
//				//easyui的关闭
//				orgDeptParent.setState("closed");
//				orgDeptParent.getChildren().add(orgDept);
//			}
//		}
		return orgDepts;
	}

	@Override
	public List<OrgDeptExtend> selectOrgDeptByPkHrorgService(String pkHrorgs) {
		// 获取所有部门信息
		//List<OrgDept> orgDepts = signCardSingleMapper.selectOrgDeptByPkHrorg(pkHrorg);
		List<OrgDeptExtend> orgDepts=null;
		if(pkHrorgs.indexOf(",")>0){
			String[] split = pkHrorgs.split(",");
			List<String> strings = Arrays.asList(split);
			orgDepts = signCardSingleMapper.selectOrgDeptByPkHrorgs(strings);
		}else{
			orgDepts = signCardSingleMapper.selectOrgDeptByPkHrorg(pkHrorgs);
		}
		// 存储map
		Map<String, OrgDeptExtend> mapOrgDept = new HashMap<String, OrgDeptExtend>();
		List<OrgDeptExtend> parent = new ArrayList<OrgDeptExtend>();
		for (OrgDeptExtend orgDept : orgDepts) {
			mapOrgDept.put(orgDept.getPkDept(), orgDept);
			if (orgDept.getPkFatherorg().equals("~")) {
				parent.add(orgDept);
			}
		}
		for (OrgDeptExtend orgDept : orgDepts) {
			// 从map中查找到父对象，把自己存进父对象的属性Children中
			OrgDeptExtend orgDeptParent = mapOrgDept.get(orgDept.getPkFatherorg());
			if (orgDeptParent != null) {
				orgDeptParent.setState("closed");
				orgDeptParent.getChildren().add(orgDept);
			}
		}
		return parent;
	}

	@Override
	public List<OrgDeptExtend> selectOrgDeptById(String id) {
		return	signCardSingleMapper.selectOrgDeptByPkId(id);
	}

	@Override
	public List<BdPsndoc> getDeptPsndocService(List<String> pkDepts) {
		return signCardSingleMapper.getDeptPsndoc(pkDepts);
	}

	@Override
	@Transactional("oracleTransactionManager")
	public DataGridData deleteTbmSignbService(List<TbmSignbExtend> tbmSignbExtends) {
		OpalUser user = getUser();
		if (user == null) {
			return new DataGridData(404, null) ;
		}
		String pkSignb = tbmSignbExtends.get(0).getPkSignb();
		List<TbmSignh> signh = signCardSingleMapper.selectTbmSignhByPkSignb(pkSignb);
		if (isSafekeeping(signh.get(0).getApplyDate(), CommonConst.currentPkOrg.get(user.getUserId()))) {
			return new DataGridData(500, "考勤期间已封存，不允许删除签卡单");
		}
		try {
			int sizeDelete = tbmSignbExtends.size();
			if (sizeDelete > 0) {
				// 选择的是全部
				if (sizeDelete == tbmSignbExtends.get(0).getTotal()) {

					String cPkSignh = CommonConst.currentPkSignh.get(user.getUserId());
					// 根据主表id 删除登记表
					if (cPkSignh != null) {

						// 根据主表id 删除登记表
						signCardSingleMapper.deleteTbmSignregByPkSignh(cPkSignh);
						// 根据主表id 删除子表
						signCardSingleMapper.deleteTbmSignbByPkSignh(cPkSignh);
						// 根据主表id 删除主表
						signCardSingleMapper.deleteTbmSignhById(cPkSignh);
						log.info("用户：" + user.getUserName() + "在[" + CommonUtils.getCurrentDateTimeString() + "]【删除】签卡单："
								+ CommonConst.currentbillCode.get(user.getUserId()) + "所有的数据");
						DataGridData dataGrid = new DataGridData(200, "删除成功！");
						// 封装当前的主键用于删除前端的主表数据
						dataGrid.setPkSignh(cPkSignh);
						return dataGrid;
					}
				} else {
					// 选择的是部分:先删登记表，再删子表
					// 先删登记表，再删子表
					for (TbmSignbExtend t : tbmSignbExtends) {
						 pkSignb = t.getPkSignb();
						if (pkSignb != null) {
							signCardSingleMapper.deleteTbmSignregByPkSignb(pkSignb);
							signCardSingleMapper.deleteTbmSignbById(pkSignb);
							log.info("用户：" + user.getUserName() + "在[" + CommonUtils.getCurrentDateTimeString() + "]【删除】签卡单 ："
									+ CommonConst.currentbillCode.get(user.getUserId()) + "子表数据");
						} else {
							throw new Exception();
						}
					}
					return new DataGridData(201, "删除成功！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.info("用户：" + user.getUserName() + "在[" + CommonUtils.getCurrentDateTimeString() + "]操作【删除】签卡单 ：" + CommonConst.currentbillCode.get(user.getUserId())
					+ "子表数据---失败");
			return new DataGridData(500, "删除失败：请稍候再试或联系管理员！");
		}

		return new DataGridData(500, "删除失败：数据不完整！");
	}

	@Override
	@Transactional("oracleTransactionManager")
	public DataGridData deleteTbmSignhService(List<TbmSignhExtend> tbmSignhExtends) {
		OpalUser user = getUser();
		if (user == null) {
			return new DataGridData(404, null);
		}

		try {

			for (TbmSignhExtend tbmSignhExtend : tbmSignhExtends) {
				if (isSafekeeping(tbmSignhExtend.getApplyDate(), CommonConst.currentPkOrg.get(user.getUserId()))) {
					return new DataGridData(500, "考勤期间已封存，不允许删除签卡单--" + tbmSignhExtend.getBillCode());
				}
				// 根据主表id 删除登记表
				String pkSignh = tbmSignhExtend.getPkSignh();
				if (pkSignh != null) {
					// 删除登记表
					signCardSingleMapper.deleteTbmSignregByPkSignh(pkSignh);
					// 根据主表id 删除子表
					signCardSingleMapper.deleteTbmSignbByPkSignh(pkSignh);
					// 根据主表id 删除主表
					signCardSingleMapper.deleteTbmSignhById(pkSignh);
				}
				log.info("用户：" + user.getUserName() + "在[" + CommonUtils.getCurrentDateTimeString() + "]操作【删除】签卡单 ："
						+ tbmSignhExtend.getBillCode() + "所有的数据");
			}
			return new DataGridData(200, "删除成功！");
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new DataGridData(500, "删除失败：请稍候再试或联系管理员！");
		}
	}
	
	//判断是否已封存
	public Boolean isSafekeeping(String dateTime,String pkOrg) {
		String[] date=dateTime.split("-"); 
		String sealflag = signCardSingleMapper.isSealflag(date[0], date[1], pkOrg);
		if(sealflag.equals("Y")) {
			return true;
		}
		return false;
	}

	@Override
	public List<BdDefdoc> getBdDefdocService() {
		return signCardSingleMapper.getBdDefdoc();
	}

	@Override
	@Transactional("oracleTransactionManager")
	public ReturnMessageData updateTbmSignbByPkSignbService(TbmSignbExtend tbmSignbExtend) {
		OpalUser user = getUser();
		if(user==null) {
			return new DataGridData(404, null);
		}

		//判断时间格式与处理时间：signdate字段和Signtime字段
		try {
			//判断Signtime字段
			Date legalDate = this.isLegalDate(tbmSignbExtend.getSigntime());
			//Signtime字段人为变成：[2020-02-02 7:00:00]变回[2020-02-02 07:00:00]NC系统会报错 科长21号提出的问题，
			tbmSignbExtend.setSigntime(this.dateToString(legalDate));
			//获取字段值signdate
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String signdate = sdf.format(legalDate);
			tbmSignbExtend.setSigndate(signdate);
		} catch (Exception e) {
			return new DataGridData(500, "修改失败：时间格式不正确请按规范【2017-09-01 16:48:02】");
		}

		// 判断是否带中文(后续需要在前端修改下)
		String name = tbmSignbExtend.getName();
		if (name == null || name.length() <= 0 || isChineseChar(name)) {
			tbmSignbExtend.setName(null);
		}

		// 判断考勤封存
		String pkSignb = tbmSignbExtend.getPkSignb();
		List<TbmSignh> signh = signCardSingleMapper.selectTbmSignhByPkSignb(pkSignb);
		if (signh.size() > 0) {
			if (isSafekeeping(signh.get(0).getApplyDate(), CommonConst.currentPkOrg.get(user.getUserId()))) {
				return new DataGridData(500, "考勤期间已封存，不允许修改签卡单--");
			}
		}

		try {
			// 查询签卡登记表有无记录：tbm_signreg
			List<TbmSignreg> list = signCardSingleMapper.selectTbmSignregByPkSignb(pkSignb);
			if (list.size() > 0) {
				// 同步修改签卡时间
				signCardSingleMapper.updateTbmSignregByPkSignb(tbmSignbExtend);

			}
			int i = signCardSingleMapper.updateTbmSignbByPkSignb(tbmSignbExtend);
			if (i > 0) {
				log.info("用户：" + user.getUserName() + "在[" + CommonUtils.getCurrentDateTimeString() + "]操作【修改】签卡单："
						+ CommonConst.currentbillCode.get(user.getUserId()) + "---成功");
				return new DataGridData(200, "修改成功");
			}

		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new DataGridData(500, "修改失败：请稍候再试或联系管理员！");
		}
		return new DataGridData(500, "修改失败：建议再次进行查询有无此数据");
	}
	

	/**
	 * 判断时间格式 格式必须为“yyyy-MM-dd hh:mm:ss ”
	 * 2003-2-29 是无效的
	 * @param sDate
	 * @return
	 */
	private Date isLegalDate(String sDate) throws Exception {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return  formatter.parse(sDate);
	}

	private String dateToString(Date date) throws Exception {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return  formatter.format(date);
	}
	
	/**
	 * 判断时间格式 格式必须为“yyyy-MM-dd hh:mm:ss ”
	 * 2003-2-29 是无效的
	 * @param sDate
	 * @return
	 */
	private boolean isLegalDate2(String sDate) {
		int legalLen = 19;
		if ((sDate == null) || (sDate.length() != legalLen)) {
			return false;
		}
		
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			formatter.parse(sDate);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 判断是否带中文
	 * @param str
	 * @return
	 */
	public  boolean isChineseChar(String str) {
		boolean temp = false;
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			temp = true;
		}
		return temp;
	}
}
